package com.garmin.tw.garminpcsync.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.graphics.drawable.Drawable;

public class AsyncImageLoader extends Thread {
	interface AsyncImageCallback {
        /** @brief Called by an AsyncImageLoader upon request completion.
          * @param url Same URL as the one passed to the AsyncImageLoader constructor.
          * @param bm A Bitmap object, or null on failure.
          */
        void onImageReceived(String url, Drawable d);
    }
	
    /** @brief Start an asynchronous image fetch operation.
      * @param url The URL of the remote picture.
      * @param cb The AsyncImageCallback object you want to be notified the operation completes.
      */
    public AsyncImageLoader(String url, AsyncImageCallback cb) {
        super();
        mURL=url;
        mCallback=cb;
        //start();
    }
    
    public void run() {
        try {
        	
        	File f = new File( ((Activity)mCallback).getApplicationContext().getCacheDir(), this.getHash(this.mURL));
        	
        	if (!f.exists()) {
        		InputStream is = (InputStream) this.fetch(this.mURL);
                
        		if (f.createNewFile()) {
                    FileOutputStream fo = new FileOutputStream(f);
                    byte[] buffer = new byte[256];
                    int size;

                    while ((size = is.read(buffer)) > 0) {
                        fo.write(buffer, 0, size);
                    }
                    fo.flush();
                    fo.close();
                }
            }
        	
        	Drawable d = Drawable.createFromPath(f.getAbsolutePath());
        	
        	/*InputStream is = (InputStream) this.fetch(this.mURL);
        	Drawable d = Drawable.createFromStream(is, "src");*/
        	
        	/*String filename = Integer.toString(this.mURL.hashCode());

			File dir = ((Activity)mCallback).getApplicationContext().getDir("images",
					Context.MODE_PRIVATE);
			String location = dir.getAbsolutePath() + "/" + filename;
			
			FileOutputStream out = new FileOutputStream(location);
			Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
        	d = Drawable.createFromPath(location);*/
        	
            /*mCallback.onImageReceived(mURL, BitmapFactory.decodeStream(conn.getInputStream()));*/
        	mCallback.onImageReceived(mURL, d);
        	
        } catch (IOException e) {
            mCallback.onImageReceived(mURL, null);
        }
    }
    
    public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}
    
    private String mURL;
    private AsyncImageCallback mCallback;
    
    private String getHash(String url) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(url.getBytes());
            return new BigInteger(digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException ex) {
            // this should never happen, but just to make sure return the url
            return url;
        }
    }
}
